package hit.util.autoProductID;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 * Singleton that contains a list of {@link Plugin}s. Operates over them in
 * a "Chain of Responsibility" fashion
 */
public class ProductIdentifier {
	
	private static ProductIdentifier identifier = null;
	
	private List<Plugin> plugins;
	
	private ProductIdentifier(){
		plugins = new ArrayList<Plugin>();
	}
	
	/**
	 * Supports Singleton pattern
	 * @return a static instance of a ProductIdentifier
	 */
	public static ProductIdentifier Instance(){
		
		if (identifier == null)
			identifier = new ProductIdentifier();
		
		return identifier;
	}
	
	/**
	 * Load plugins from a configuration file
	 * @param filename The configuration file to be opened.
	 */
	public void LoadPlugins(String filename){
		
		plugins.clear();
		
		try
		{
			Document dom = LoadXMLDocument(filename);
			
			Element root = dom.getDocumentElement();
			NodeList pluginsToParse = root.getElementsByTagName("plugin");
			
			for (int i = 0; i < pluginsToParse.getLength(); i++) 
			{
				Node n = pluginsToParse.item(i);
				
				Plugin newPlugin = ParseNodeForPlugin(n);
				
				if (newPlugin != null)
					plugins.add(newPlugin);
			}
		}
		catch (Exception ex)
		{
			// Reached error. Continue on without issue.
		}
	}
	
	private Plugin ParseNodeForPlugin(Node node)
	{
		try
		{
			String attribute = node.getAttributes().getNamedItem("class").getNodeValue();
			String filename = node.getAttributes().getNamedItem("filename").getNodeValue();
			
			File file = new File(filename);
			URL[] url = new URL[]{file.toURI().toURL()};
			
			ClassLoader cl = new URLClassLoader(url);
			Class cls = cl.loadClass(attribute);
			
			
			Plugin newPlugin = (Plugin)cls.newInstance();
			
			return newPlugin;
		}
		catch (Exception ex)
		{
			// Problem loading the Plugin.
		}
		
		return null;
	}
	
	private Document LoadXMLDocument(String filename) throws ParserConfigurationException,
														SAXException, IOException
	{
		File file = new File(filename);
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document dom = db.parse(file);
		
		return dom;
	}
	
	/**
	 * Iterates through the list of plugins, asking each to try and
	 * describe a product from its barcode.
	 * @param barcode The barcode of interest
	 * @return The description of the barcode, or null if not found
	 */
	public String GetDescription(String barcode){
				
		for(Plugin p : plugins)
		{
			String result = p.GetDescription(barcode);
			if (result != null && !result.equals(""))
			{
				return result;
			}
		}
		
		return "";
	}
}
